/**
 * @description: 数据中台-任务-任务管理-新建任务
 * @author: hj
 * @update: hj(2020-01-14)
 */
import React from 'react';
import IceContainer from '@icedesign/container';
import {Button, Input, Message, Radio, Select, Tree} from '@alifd/next';
import {
  FormBinder as IceFormBinder,
  FormBinderWrapper as IceFormBinderWrapper,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import styles from './index.module.scss';
import url from '@/request'
import $http from '@/service/Services';

const axios = $http;

const {Option} = Select;
const {Group: RadioGroup} = Radio;
let form;


/**
 * list
 */
class TaskEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: {},
      id: '',
      datasources: [],
      taskList: [],
      datasourceTypeId: '',
      schames: [],
      taskDetailList: [],
      config: {
        data: null,
        visible: false,
        title: '',
        content: ''
      }
    };
    this.formChange = this.formChange.bind(this);
    this.validateAllFormField = this.validateAllFormField.bind(this);
    this.handleCheck = this.handleCheck.bind(this);
  }

  /**
   * 在渲染前调用,在客户端也在服务端
   */
  componentWillMount = () => {
    const params = new URLSearchParams(this.props.location.search);
    const id = params.get('id');
    this.setState({
      id: id,
    }, () => {
      this.getAllDatasourceList();
      if (id) {
        const that = this;
        axios.get(url.url + '/v1/taskDetail/getTTaskDetailById/' + id)
          .then(function (response) {
            const {data} = response;
            if (data.code === 1) {
              Message.warning(data.message ? data.message : data.data);
            } else {
              that.setState({
                value: data.data
              })
            }
          })
          .catch(function (error) {
            Message.error(error.message);
          })
      }
    });
  };

  /**
   * 获取所有数据源列表
   */
  getAllDatasourceList = () => {
    const that = this;
    axios.get(url.url + '/v1/tDataSource/getAllDatasourceList').then(function (response) {
      const {data} = response;
      if (data.code === 1) {
        Message.warning(data.message ? data.message : data.data);
      } else {
        that.setState({
          datasources: data.data
        })
      }
    })
      .catch(function (error) {
        Message.error(error.message);
      });
  };
  /**
   * 获取一级，二级菜单接口
   */
  getAllTableList = (event) => {
    const that = this;
    axios.get(url.url + '/v1/tDataSource/getDatabaseBySourceId/' + event)
      .then(function (response) {
        const {data} = response;
        if (data.code === 1) {
          Message.warning(data.message ? data.message : data.data);
        } else {
          const arr = data.data;
          that.setState({
            schames: arr
          })
        }
      })
      .catch(function (error) {
        console.error(error);
        Message.error(error.message);
      })
  };

  /* 表改变
  * @param formValue
  */
  formChange = (formValue) => {
    this.setState({
      value: formValue
    })
  };
  /**
   * 表验证
   */
  validateAllFormField = () => {
    form.validateAll((errors, values) => {
      try {
        if (errors) {
          Message.warning('请填写必要的数据.');
          return;
        }
        const that = this;
        axios.post(url.url + '/v1/taskDetail/saveOrUpdateTaskDetail', values)
          .then(function (response) {
            const {data} = response;
            if (data.code === 1) {
              Message.warning(data.message ? data.message : data.data);
            } else {
              Message.success('操作成功.');
              that.props.history.go(-1);
            }
          })
          .catch(function (error) {
            console.error(error);
            Message.error(error.message);
          })
      } catch (e) {
        console.error(e);
      }
    });
  };

  /**
   *
   * @param keys
   * @param info
   */
  handleCheck(keys, info) {
    this.setState({
      checkedKeys: keys,
      info: info
    });
  }

  /**
   * 表
   * @returns {*}
   */
  render() {
    return (
      <div>
        <div className='container-header'>
          <p style={{display: 'inline-block'}}>新建任务</p>
          <Button type="normal" size="small" className='next-btn-normal table-btn-return' style={{float: 'right'}}>
            <a onClick={() => {
              this.props.history.go(-1)
            }}> 返回</a>
          </Button>
        </div>


        <IceContainer className='container-main'>
          <IceFormBinderWrapper
            value={this.state.value}
            onChange={this.formChange}
            ref={formRef => form = formRef}
          >
            <div className={styles.formContent}>

              <div className={styles.formItem}>
                <div className={styles.formLabel}><span className={styles.red}>*</span>任务名称：</div>
                <IceFormBinder
                  required
                  triggerType="onBlur"
                  message="任务名称不能为空"
                  name="name"
                >
                  <Input
                    maxLength={20}
                    placeholder="请填写任务名称"
                    className={styles.inputNme}
                  />
                </IceFormBinder>
                <div className={styles.formError}>
                  <IceFormError name="name"/>
                </div>
              </div>
              <div className={styles.formItem}>
                <div className={styles.formLabel}><span
                  className={styles.red}>*</span>数据源：
                </div>
                <IceFormBinder required name="datasourceId" message="数据源不能为空">
                  <Select
                    placeholder="请选择"
                    className={styles.inputNme}
                    onChange={this.getAllTableList}
                  >
                    {
                      this.state.datasources.map(
                        o => {
                          return (<Option value={o.id}>{o.name}</Option>)
                        }
                      )
                    }
                  </Select>
                </IceFormBinder>
                <div className={styles.formError}>
                  <IceFormError name="datasourceId"/>
                </div>
              </div>
              <div>
                <div className={styles.formItem}>
                  <div className={styles.formLabel}><span
                    className={styles.red}>*</span>目标数据源：
                  </div>
                  <IceFormBinder required name="targetId" message="目标数据源不能为空">
                    <Select
                      placeholder="请选择"
                      className={styles.inputNme}
                    >
                      {
                        this.state.datasources.map(
                          o => {
                            return (<Option value={o.id}>{o.name}</Option>)
                          }
                        )
                      }
                    </Select>
                  </IceFormBinder>
                  <div className={styles.formError}>
                    <IceFormError name="datasourceId"/>
                  </div>
                </div>
                <div className={styles.formItem}>
                  <div className={styles.formLabel}>同步数据：</div>
                  <IceFormBinder required name="tableNames" message="目标数据源不能为空">
                    <Select name="tableNames" style={{width: 300}} mode="multiple">
                      {
                        Array.isArray(this.state.schames) &&
                        this.state.schames.length > 0 &&
                        this.state.schames.map(
                          o => {
                            return (
                              <Select.Option value={o.name}>{o.name}</Select.Option>
                            )
                          }
                        )
                      }
                    </Select>
                  </IceFormBinder>
                  <div className={styles.formError}>
                    <IceFormError name="datasourceId"/>
                  </div>

                </div>
              </div>
              <div className={styles.formItem}>
                <div className={styles.formLabel}>任务描述:</div>
                <IceFormBinder
                  triggerType="onBlur"
                  name="content"
                >
                  <Input.TextArea
                    maxLength={50}
                    rows={8}
                    hasLimitHint
                    placeholder="请填写任务描述信息"
                    className={styles.inputNme}
                  />
                </IceFormBinder>
                <div className={styles.formError}>
                  <IceFormError name="content"/>
                </div>
              </div>
              <Button
                type="primary"
                className='sync-btn-submit'
                onClick={this.validateAllFormField}
              >
                提 交
              </Button>
              <Button
                type="primary"
                className='zgph-btn-cancel'
                onClick={() => {
                  this.props.history.go(-1)
                }}
              >
                取消
              </Button>
            </div>
          </IceFormBinderWrapper>
        </IceContainer>
      </div>
    );
  }

}

export default TaskEdit;
